package com.apexsoft.monitor.front.console.magent.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apexsoft.front.common.support.Result;
import com.apexsoft.monitor.front.console.host.om.Host;
import com.apexsoft.monitor.front.console.host.service.HostService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;

/**
 * 监控进程
 */
@Service("magentService")
public class MagentService {
    private static final Logger log = LogManager.getRootLogger();
    @Autowired
    @Qualifier("hostService")
    private HostService hostService = null;

    /**
     * 查询监控程序的状态
     * @return
     */
    public JSONObject getHostStatus(){
        JSONObject result = new JSONObject();
        JSONArray hostList = new JSONArray();
        DecimalFormat df  = new DecimalFormat("######0.00");
        try{
            if(MonitorThread.hostList!=null &&MonitorThread.hostList.size()>0){
                for(Host host:MonitorThread.hostList){
                    JSONObject tempHost = new JSONObject();
                    tempHost.putAll(JSONObject.parseObject(JSON.toJSONString(host)));
                    MagentThread mt = (MagentThread)MonitorThread.magentMap.get(host.getId()+"");
                    if(mt!=null && mt.getMagentInfo()!=null){
                        tempHost.putAll(mt.getMagentInfo());
                        tempHost.put("mem_total",df.format(mt.getMagentInfo().getDoubleValue("mem_total")/1024/1024/1024));
                        tempHost.put("mem_used_percent",df.format(mt.getMagentInfo().getDoubleValue("mem_used_percent")));
                        tempHost.put("disk_used_percent",df.format(mt.getMagentInfo().getDoubleValue("disk_used_percent")));
                    }
                    hostList.add(tempHost);
                }
                result.put(Result.CODE, Result.SC_0001);
                result.put(Result.NOTE, "");
                result.put(Result.ROWS, hostList);
            }else{
                result.put(Result.CODE, Result.EC_1000);
                result.put(Result.NOTE, "暂无主机列表");
            }
        }catch(Exception e){
            result.put(Result.CODE, Result.EC_1000);
            result.put(Result.NOTE, "获取主机列表异常"+e.getMessage());
        }
        return result;
    }
}
